package com.module.overview.ui.cardHistoryDetails.provider

import android.graphics.Typeface
import android.view.View
import android.widget.TextView
import com.chad.library.adapter.base.provider.BaseItemProvider
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.common.app.core.RouterHub
import com.common.app.data.bean.KeyBundle
import com.common.app.data.bean.home.ScoringFactorsModel
import com.common.app.data.bean.overView.HistoryDetailsModel
import com.common.app.data.repository.HomeApi
import com.common.app.helper.RouterHelper
import com.common.app.utls.TimeUtils
import com.module.ble.utils.AllCardTypeConfig
import com.module.overview.R
import com.common.base.app.extras.doOnIOThread
import com.common.base.app.extras.doOnUiThread
import com.common.base.app.extras.setOnClickListener
import com.common.base.app.extras.yes
import com.common.base.data.CommonBean
import com.common.base.utils.AppUtils
import com.common.base.utils.MathUtil
import com.common.base.utils.SpanUtils
import com.common.base.utils.ViewUtils
import com.common.base.widget.CustomTextView
import com.module.ble.data.bean.CusChartData
import com.module.ble.repo.SleepInfoRepo
import com.module.ble.utils.groupSleepDataByQualityAndTime
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.launch
import rxhttp.toFlow
import rxhttp.wrapper.param.RxHttp

/**
 *
 * 作者：sosou
 *
 * 版本：1.0
 *
 * 创建日期：2025/7/12
 *
 * 描述：睡眠-睡眠状态卡片
 *
 * 修订历史：完成度100%
 *
 */
class OvSleepStateCardProvider(time:Long,
    override val itemViewType: Int = AllCardTypeConfig.TYPE_CARD_SLEEP_STATE_VALUE,
    override val layoutId: Int = R.layout.overview_sleep_state_crad_provider
) : BaseItemProvider<HistoryDetailsModel>() {

    private var curTime = time
    private val curTimePair = TimeUtils.getTimeRangeForSleep(curTime)

    var theDaySleepDuration = -1L//睡眠总时长，单位：分钟
    var theDayStayBedDuration = -1L//卧床总时长，单位：分钟
    var theDaySleepEfficiency = -1//睡眠效率

    private var tvSleepTotalDuration: TextView? = null
    private var tvSleepEfficiency : TextView? = null
    private var tvSleepValue : TextView? = null

    private var requestJob: Job? = null
    var scope = CoroutineScope(Dispatchers.IO)

    init {
    }

    override fun convert(helper: BaseViewHolder, item: HistoryDetailsModel) {

        getNightSleepData()

        getSleepScoringFactors()
    }

    override fun onViewHolderCreated(viewHolder: BaseViewHolder, viewType: Int) {

        tvSleepTotalDuration = viewHolder.getView(R.id.tvSleepTotalDuration)
        tvSleepEfficiency = viewHolder.getView(R.id.tvSleepEfficiency)
        tvSleepValue = viewHolder.getView(R.id.tvSleepValue)

        viewHolder.getView<CustomTextView>(R.id.tvFactorsHint).setOnClickListener(onClick = object : View.OnClickListener {
            override fun onClick(p0: View?) {
                RouterHelper.navigationPostcard(RouterHub.ROUTER_HOME_SCORING_FACTORS)
                    .withInt(KeyBundle.BUNDLE_KEY, 1)
                    .withString(KeyBundle.EXPAND_DATA, TimeUtils.getYearMonthDay(curTime))
                    .navigation()
            }
        })
        super.onViewHolderCreated(viewHolder, viewType)
    }

    /**
     * 获取昨晚睡眠数据
     */
    private fun getNightSleepData(){
        if (curTime <=0 ) return
        theDaySleepDuration = 0
        theDayStayBedDuration = 0
            doOnIOThread {
            SleepInfoRepo.instance.findByTimeRangeByNight(curTimePair.first, curTimePair.second)?.let { listIt->
                listIt.sortedBy { it.createdTime }//按时间排序（升序）
                val sleepData: MutableList<CusChartData>
                if (listIt.isNotEmpty()) {
                    sleepData = groupSleepDataByQualityAndTime(listIt) as MutableList<CusChartData>
                    sleepData.forEach {sleepDataIt->
                        theDaySleepDuration += if (sleepDataIt.status==1||sleepDataIt.status==2||sleepDataIt.status==3) sleepDataIt.timeLong else 0
                        theDayStayBedDuration += sleepDataIt.timeLong
                    }

                    theDaySleepEfficiency = ((MathUtil.div(theDaySleepDuration.toString(),theDayStayBedDuration.toString(),false)?:"0").toFloat() * 100).toInt()

                    val tvLastSList = TimeUtils.formatTimeToList(theDayStayBedDuration*60000)

                    doOnUiThread {
                        tvSleepTotalDuration?.let { viewIt ->
                        SpanUtils.create()
                            .addForeColorSection(
                                tvLastSList[1].toString(),
                                ViewUtils.getColor(
                                    R.color.text_content
                                )
                            )
                            .setAbsSize(tvLastSList[1].toString(), 16)
                            .setStyle(tvLastSList[1].toString(), Typeface.BOLD)
                            .addForeColorSection(
                                AppUtils.getString(R.string.common_hours_hint),
                                ViewUtils.getColor(
                                    R.color.c_7f7f7f
                                )
                            )
                            .addForeColorSection(
                                tvLastSList[2].toString(),
                                ViewUtils.getColor(
                                    R.color.text_content
                                )
                            )
                            .setAbsSize(tvLastSList[2].toString(), 16)
                            .setStyle(tvLastSList[2].toString(), Typeface.BOLD)
                            .addForeColorSection(
                                AppUtils.getString(R.string.common_score_hint),
                                ViewUtils.getColor(
                                    R.color.c_7f7f7f
                                )
                            )
                            .showIn(viewIt)
                        }

                        val tvLastStr = if(theDaySleepEfficiency >=0) theDaySleepEfficiency.toString() else ViewUtils.getString(
                            R.string.common_rail_unit
                        )

                        tvSleepEfficiency?.let { viewIt ->
                            SpanUtils.create()
                                .addForeColorSection(
                                    tvLastStr,
                                    ViewUtils.getColor(
                                        R.color.text_content
                                    )
                                )
                                .setAbsSize(tvLastStr, 16)
                                .setStyle(tvLastStr, Typeface.BOLD)
                                .addForeColorSection("${ViewUtils.getString(R.string.common_bfb_unit)}",ViewUtils.getColor(R.color.c_7f7f7f))
                                .showIn(viewIt)
                        }
                    }
                }
            }
        }
    }

    // 手动取消请求
    fun cancelRequest() {
        requestJob?.cancel()
        requestJob = null
    }

    private fun getSleepScoringFactors() {
        // 取消之前的请求
        requestJob?.cancel()

        requestJob = scope.launch {
            RxHttp.postJson(HomeApi.GET_SLEEP_SCORING_FACTORS)
                .add("date", TimeUtils.getYearMonthDay(curTime))
                .toFlow<CommonBean<ScoringFactorsModel>>()
                .catch { e ->
                    // 处理异常
                }.collect { responseIt->
                    responseIt.isSuccess().yes {
                        responseIt.Data?.let { dataIt->
                            doOnUiThread {
                                tvSleepValue?.text = dataIt.total_score.toInt().toString()
                            }
                        }
                    }
                }
        }
    }
}